package com.example.music;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;


import android.Manifest;
import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.hardware.display.DisplayManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MusicMain extends AppCompatActivity {

    public static List<MediaBean> list = new ArrayList<>();

    ImageView musicback, left, right;
    public static ImageView pause, imgvoice;
    public static TextView texttile, textauther, voiceshow, thistime, alltime;
    public static SeekBar seekBar, seekBarvoice;
    public static MediaPlayer mediaPlayer;
    public static AudioManager audioManager;
    public static Context context;
    public static int posion, back;


    boolean voice = true;
    public static int voicemax;
    public static int thisvoice;
    int i;


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_main);

        setView();

        if (Build.VERSION.SDK_INT > 24 && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, 1);

        } else {

            LocalVideo.getVideoFile(list, Environment.getExternalStorageDirectory());

            if (list.size() != 0) {
                play();

                getFuPing();

            }

        }


        initView();


    }

    public static void playfu(String what) {
        if (what.equals("left")) {
            posion--;


        } else if (what.equals("right")) {
            posion++;

        }
        LocalVideo.getVideoFile(list, Environment.getExternalStorageDirectory());

        MediaBean mediaBean = list.get(posion);

        texttile.setText(mediaBean.getSongname(context));


        textauther.setText(mediaBean.getVauther(context));

        mediaPlayer.reset();

        try {
            mediaPlayer.setDataSource(list.get(posion).path);
            mediaPlayer.prepare();
            mediaPlayer.start();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    private void initView() {

        musicback.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onClick(View view) {

                back = 1;
                getFuPing();

                finish();

            }
        });

        pause.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onClick(View view) {
                if (list.size() > 0) {
                    if (!mediaPlayer.isPlaying()) {

                        mediaPlayer.start();


                        pause.setBackgroundResource(R.drawable.music_play);
                        FuMusicActivity.pause.setBackgroundResource(R.drawable.music_play);

                    } else {

                        mediaPlayer.pause();
                        pause.setBackgroundResource(R.drawable.pause);
                        FuMusicActivity.pause.setBackgroundResource(R.drawable.pause);
                    }
                } else {
                    Toast.makeText(MusicMain.this, "暂无数据", Toast.LENGTH_SHORT).show();
                }

            }
        });
        imgvoice.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onClick(View view) {
                if (voice == true) {

                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
                    imgvoice.setBackgroundResource(R.drawable.mute_select);

                    FuMusicActivity.imgvoice.setBackgroundResource(R.drawable.mute_select);
                    voice = false;

                } else {

                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, thisvoice, 0);
                    imgvoice.setBackgroundResource(R.drawable.voice_select);
                    FuMusicActivity.imgvoice.setBackgroundResource(R.drawable.voice_select);

                    voice = true;


                }
            }
        });

        left.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onClick(View view) {
                if (list.size() == 0) {
                    Toast.makeText(MusicMain.this, "暂无数据", Toast.LENGTH_SHORT).show();
                } else {
                    if (posion == 0) {
                        Toast.makeText(MusicMain.this, "当前是第一首", Toast.LENGTH_SHORT).show();
                    } else {
                        posion--;
                        getFuPing();
                        play();
                        mediaPlayer.start();

                        pause.setBackgroundResource(R.drawable.music_play);

                    }
                }
            }
        });

        right.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onClick(View view) {
                if (list.size() == 0) {
                    Toast.makeText(MusicMain.this, "暂无数据", Toast.LENGTH_SHORT).show();

                } else {
                    posion++;
                    getFuPing();
                    play();
                    mediaPlayer.start();

                    pause.setBackgroundResource(R.drawable.music_play);

                }
            }
        });
    }

    private void setView() {

        musicback = findViewById(R.id.musicback);
        left = findViewById(R.id.left);
        pause = findViewById(R.id.pause);
        right = findViewById(R.id.right);
        imgvoice = findViewById(R.id.imgvoice);
        texttile = findViewById(R.id.texttile);
        textauther = findViewById(R.id.textauther);
        voiceshow = findViewById(R.id.voiceshow);
        thistime = findViewById(R.id.thistime);
        alltime = findViewById(R.id.alltime);
        seekBar = findViewById(R.id.seekBar);
        seekBarvoice = findViewById(R.id.seekBarvoice);

        mediaPlayer = new MediaPlayer();
        audioManager = (AudioManager) MusicMain.this.getSystemService(Context.AUDIO_SERVICE);


    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            if (list.size() == 0) {
                play();
                getFuPing();
            } else {
                texttile.setText("无媒体数据");
            }

        } else {
            Toast.makeText(MusicMain.this, "已拒绝权限，暂无数据", Toast.LENGTH_SHORT).show();
            texttile.setText("无媒体数据");
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void play() {

        LocalVideo.getVideoFile(list, Environment.getExternalStorageDirectory());

        MediaBean mediaBean = list.get(posion);

        texttile.setText(mediaBean.getSongname(context));


        textauther.setText(mediaBean.getVauther(context));

        mediaPlayer.reset();

        try {
            mediaPlayer.setDataSource(list.get(posion).path);
            mediaPlayer.prepare();
            mediaPlayer.start();

        } catch (IOException e) {
            e.printStackTrace();
        }
        SetBar();

        SetVoiceBar();

    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void getFuPing() {
        DisplayManager displayManager = (DisplayManager) MusicMain.this.getSystemService(Context.DISPLAY_SERVICE);

        Display[] displays = displayManager.getDisplays();
        if (displays.length > 1) {

            Intent intent = new Intent(MusicMain.this, FuMusicActivity.class);

            intent.setClassName(getPackageName(), getPackageName() + ".FuMusicActivity");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

            ActivityOptions options = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                options = ActivityOptions.makeBasic();
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                options.setLaunchDisplayId(displays[1].getDisplayId());
            }
            startActivity(intent, options.toBundle());
        } else {
            Toast.makeText(MusicMain.this, "未开启副屏", Toast.LENGTH_SHORT).show();
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void SetVoiceBar() {
        voicemax = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        seekBarvoice.setMax(voicemax);

        thisvoice = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);


        seekBarvoice.setProgress(thisvoice);


        voiceshow.setText("当前音量：" + thisvoice * 100 / voicemax + "%");


        seekBarvoice.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
                thisvoice = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

                seekBarvoice.setProgress(thisvoice);
                FuMusicActivity.seekBarvoice.setProgress(thisvoice);
                if (thisvoice == 0) {
                    imgvoice.setBackgroundResource(R.drawable.mute_select);
                    voiceshow.setText("静音状态");
                    FuMusicActivity.voiceshow.setText("静音状态");
                    FuMusicActivity.imgvoice.setBackgroundResource(R.drawable.mute_select);

                } else {
                    voiceshow.setText("当前音量：" + thisvoice * 100 / voicemax + "%");
                    FuMusicActivity.voiceshow.setText("当前音量：" + thisvoice * 100 / voicemax + "%");

                    imgvoice.setBackgroundResource(R.drawable.voice_select);
                    FuMusicActivity.imgvoice.setBackgroundResource(R.drawable.voice_select);

                }


            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

    }

    private void SetBar() {
        seekBar.setMax(mediaPlayer.getDuration());
        alltime.setText(FormatTime(mediaPlayer.getDuration()));
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                seekBar.setProgress(mediaPlayer.getCurrentPosition());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        thistime.setText(FormatTime(mediaPlayer.getCurrentPosition()));


                    }
                });
            }
        };
        timer.schedule(timerTask, 1000, 1000);

    }




    private String FormatTime(int duration) {
        SimpleDateFormat format = new SimpleDateFormat("mm:ss");

        String time = format.format(new Date(duration));
        return time;
    }

}